package com.singzi.leetcode.N200;

import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeMap;

public class T0146 {
}
class LRUCache {
    private HashMap<Integer, int[]> map;//(key, value)
    private TreeMap<Integer, Integer> treeMap;//(更新時間， key)
    private final int cnt;
    private int time;
    public LRUCache(int capacity) {
        this.map = new HashMap<>();
        this.cnt = capacity;
        this.time = 0;

    }

    public int get(int key) {
        if(map.get(key) == null) return -1;
        else{
            treeMap.remove(map.get(key)[1]);
            time++;
            map.get(key)[1] = time;
            treeMap.put(time, key);
            return map.get(key)[0];
        }
    }
    public void put(int key, int value) {
        if(map.containsKey(key)){
            treeMap.remove(map.get(key)[1]);
            time++;
            treeMap.put(time, key);
            map.get(key)[0] = value;
            map.get(key)[1] = time;
        }
        int []temp = new int[2];
        if(map.size() == cnt){
            map.remove(treeMap.get(treeMap.firstKey()));
            treeMap.remove(treeMap.firstKey());
        }
        temp[0] = value;
        time++;
        temp[1] = time;
        map.put(key, temp);
        treeMap.put(time, key);

    }
}